/*
 * util.cpp
 *
 *  Created on: 05/12/2008
 *      Author: fernando
 */

#include "util.h"

#include <exception>
#include <string>
#include <map>
#include <sstream>
#include <istream>
#include <iostream>
#include <fstream>

using std::exception;
using std::string;
using std::map;
using std::endl;
using std::ofstream;
using std::ifstream;

namespace util {

void normalize_space(string& origin, int position, int size,
		string& destination) {
	unsigned int pos, end;

	if (size < 0)
		size = origin.size();

	pos = position;
	while (origin.at(pos) == ' ')
		pos++;

	end = (position + size);
	if (end > origin.size())
		end = origin.size();
	while (origin.at(end - 1) == ' ')
		end--;

	while (pos < end) {
		destination.push_back(origin.at(pos++));
	}
}

void dump_map(map<const string, string>& the_map, string filename)
		throw (StreamException) {
	ofstream out(filename.c_str());
	try {
		out.exceptions(ifstream::failbit);

		out << "# automatically generated properties file" << endl;
		map<const string, string>::iterator iter;
		for (iter = the_map.begin(); iter != the_map.end(); ++iter) {
			out << iter->first << " = " << iter->second << endl;
		}

		out.close();

	} catch (exception& ex) {
		try {
			if (out != NULL && out.is_open()) {
				out.close();
			}
		} catch (exception&) {
			// do nothing
		}
		throw StreamException(ex.what());
	}
}

void load_map(map<const string, string>& the_map, string filename)
		throw (StreamException) {
	ifstream in(filename.c_str(), ifstream::in);
	try {
		if (!in.is_open()) {
			throw StreamException("Cannot open file.");
		}

		int pos = 0;
		string line;
		string key;
		string value;

		while (!in.eof()) {
			getline(in, line);
			pos = line.find('=', 0);
			if (pos > 0) {
				key.clear();
				value.clear();
				normalize_space(line, 0, pos, key);
				normalize_space(line, pos + 1, string::npos, value);
				the_map[key] = value;
			}
		}

		in.close();

	} catch (StreamException& ex) {
		throw ex;

	} catch (exception& ex) {
		try {
			if (in != NULL && in.is_open()) {
				in.close();
			}
		} catch (...) {
			// do nothing
		}
		throw StreamException(ex.what());
	}
}

}
